<?php

namespace App\ApiBackend\Admin;

use App\Domains\AdminDomain;
use App\Http\Controllers\ApiBaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

/**
 *  用户信息
 */
class PersonUpdate extends ApiBaseController
{

  /**
   * 参数检查
   */
  protected function check(): void
  {
    $operate = request('operate');
    // 规则
    $ruleArr = [
      'operate' => 'required'
    ];
    switch ($operate) {
      case 'avatar':
        $ruleArr['avatar'] = 'required';
        break;
      case 'info':
        break;
      case 'password':
        $ruleArr['password'] = 'required';
        $ruleArr['passwordNew'] = 'required';
        break;
    }
    try {
      request()->validate($ruleArr);
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = $exception->getMessage();
    }
  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    $adminId = \request()->user()->id;
    $operate = request('operate');
    // 规则
    $updateArr = [];
    $errorMsg = '';
    switch ($operate) {
      case 'avatar':
        $updateArr['avatar'] = request('avatar');
        break;
      case 'info':
        $updateArr['email'] = request('email');
        $updateArr['name'] = request('name');
        $updateArr['phone'] = request('phone');
        break;
      case 'password':
        //检测密码
        $password = DB::table('admin')->where('id', request()->user()->id)->value('password');
        if (!Hash::check(\request('password'), $password)) {
          $errorMsg = "登录密码不正确";
        }
        $updateArr['password'] = Hash::make(request('passwordNew'));
        break;
    }
    if ($errorMsg) {
      $this->result["code"] = 1;
      $this->result["message"] = $errorMsg;
      return;
    }

    //数据
    try {
      $adminInfo = DB::table('admin')->where('id', $adminId)->update($updateArr);
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = "失败: " . $exception->getMessage();
    }


    return;
  }
}
